package com.ca.ridersclubapplication;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.adapter.PaperAdapter;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.LongEntity;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.ClubRequester;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.ClubDto;
import com.ca.ridersclubapplication.request.dto.ClubGradeDto;
import com.ca.ridersclubapplication.request.dto.PaperCardDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ImageCacheUtils;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.ScoreUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.bar.ClubTitleBar;
import com.ca.ridersclubapplication.view.bar.MiniScoreProcessBar;
import com.ca.ridersclubapplication.view.card.BigInfoCard;
import com.ca.ridersclubapplication.view.card.ScoreCard;

import java.util.List;

public class ClubActivity extends ImmersiveActivity {


    private Long clubId;

    private boolean isFollow = false;
    private boolean isWant = false;
    private boolean isPost = false;

    private Long startId =  Long.MAX_VALUE;
    private boolean canRequest = true;


    private NestedScrollView nsv;

    //  标题栏
    private ConstraintLayout titleCL;
    private ClubTitleBar clubTitleBar;

    //  背景图
    private ImageView bgView;

    //  信息卡片
    private BigInfoCard bigInfoCard;

    //  评分卡片
    private ScoreCard scoreCard;

    //  动态列表
    private RecyclerView rv;
    private final PaperAdapter adapter = new PaperAdapter(this, null);
    private ProgressBar progressBar;

    //  添加按钮
    private ConstraintLayout addButton;

    //  用于发布文章后重新请求回调视图
    private CallbackView callbackView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_club);

        //  加载数据
        initData();

        //  加载视图
        initView();

        //  加载监听器
        initListener();

        //  请求数据
        loadData();
    }

    private void initData() {
        Intent intent = getIntent();
        clubId = intent.getLongExtra("clubId", 0L);
        if (clubId == 0) {
            finishAfterTransition();
        }
    }

    private void initView() {

        nsv = findViewById(R.id.nsv);

        //  顶部标题栏
        titleCL = findViewById(R.id.cl_title);
        clubTitleBar = findViewById(R.id.bar_clubTitle);

        clubTitleBar.imageView.setAlpha(0f);
        clubTitleBar.followButton.setAlpha(0f);
        clubTitleBar.nameView.setAlpha(0f);
        titleCL.setElevation(0f);

        //  背景图
        bgView = findViewById(R.id.iv_clubBg);

        //  信息卡片
        bigInfoCard = findViewById(R.id.card_bigInfo);

        //  评分卡片
        scoreCard = findViewById(R.id.card_score);

        //  动态列表
        rv = findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rv.setAdapter(adapter);
        rv.setNestedScrollingEnabled(false);

        //  进度条
        progressBar = findViewById(R.id.bar_progress);

        //  添加按钮
        addButton = findViewById(R.id.cl_addButton);

        //  回调视图
        callbackView = new CallbackView() {
            @Override
            public void update() {
                Handleable data = DataHandler.getData("AddPaper");
                if (data instanceof BooleanEntity) {
                    if (((BooleanEntity) data).getValue()) {
                        //  如果有文章发布，则请求最新一篇文章，追加到头部
                        startId = Long.MAX_VALUE;
                        PaperRequester.getLastPaper(
                                ClubActivity.this,
                                DataHandler.getToken(ClubActivity.this).getId(),
                                new AfterExecutor<PaperCardDto>() {
                                    @Override
                                    public void execute(Result<PaperCardDto> result) {
                                        PaperCardDto dto = result.getData();
                                        if (result.isSuccess() && dto != null) {
                                            //  追加到顶部
                                            adapter.appendPaperToTop(dto);
                                        }
                                    }
                                });
                    }
                }
            }
        };
        DataHandler.putView("AddPaper", callbackView);
    }

    private void initListener() {


        //  监听NSV滑动事件，调整标题栏样式（隐藏、显示头像、海拔等）
        nsv.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> bigInfoCard.post(() -> {

            if (scrollY < bgView.getHeight() - 64) {
                clubTitleBar.imageView.setAlpha(0f);
                clubTitleBar.followButton.setAlpha(0f);
                clubTitleBar.nameView.setAlpha(0f);
                titleCL.setAlpha(0f);
                titleCL.setElevation(0f);
                return;
            }

            float ratio = (scrollY - bgView.getHeight() * 0.25f) / (bgView.getHeight());
            float alpha = ratio > 1 ? 1 : ratio;
            clubTitleBar.imageView.setAlpha(alpha);
            clubTitleBar.followButton.setAlpha(alpha);
            clubTitleBar.nameView.setAlpha(alpha);
            titleCL.setAlpha(alpha);
            titleCL.setElevation(ratio > 1 ? 4 : ratio * 4);

            //  滑动到底部则加载新的文章数据
            if (!nsv.canScrollVertically(1)) {
                listPaper();
            }
        }));

        //  返回按钮点击
        clubTitleBar.backView.setOnClickListener(v -> {
            finishAfterTransition();
        });

        //  关注按钮
        View.OnClickListener followListener = v -> {
            if (!isFollow) {
                ClubRequester.addFollow(this, clubId, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            clubTitleBar.followButton.setText("取关");
                            bigInfoCard.followButton.setText("取关");
                            clubTitleBar.followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                            bigInfoCard.followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                            clubTitleBar.followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                            bigInfoCard.followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                            list3FansId();
                            isFollow = true;
                            DataHandler.putData(new LongEntity("FollowCount:" + DataHandler.getToken(ClubActivity.this).getId(), 1L));
                        }
                        else {
                            Toast.makeText(ClubActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
            else {
                ClubRequester.deleteFollow(this, clubId, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            clubTitleBar.followButton.setText("关注");
                            bigInfoCard.followButton.setText("关注");
                            clubTitleBar.followButton.setTextColor(getResources().getColor(R.color.white_text));
                            bigInfoCard.followButton.setTextColor(getResources().getColor(R.color.white_text));
                            clubTitleBar.followButton.setBackgroundColor(getResources().getColor(R.color.primary));
                            bigInfoCard.followButton.setBackgroundColor(getResources().getColor(R.color.primary));
                            isFollow = false;
                            list3FansId();
                            DataHandler.putData(new LongEntity("FollowCount:" + DataHandler.getToken(ClubActivity.this).getId(), -1L));
                        }
                        else {
                            Toast.makeText(ClubActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        };
        clubTitleBar.followButton.setOnClickListener(followListener);
        bigInfoCard.followButton.setOnClickListener(followListener);

        //  想买按钮点击
        scoreCard.wantButton.setOnClickListener(v -> {
            if (!isWant) {
                ClubRequester.addWant(this, clubId, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            //  请求成功，增加人数
                            scoreCard.setWantCount(scoreCard.getWantCount() + 1);
                            scoreCard.wantButton.setText("取消");
                            scoreCard.wantButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                            scoreCard.wantButton.setTextColor(getResources().getColor(R.color.secondary_text));
                            isWant = true;
                        }
                        else {
                            Toast.makeText(ClubActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
            else {
                ClubRequester.deleteWant(this, clubId, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            //  请求成功，减少人数
                            scoreCard.setWantCount(scoreCard.getWantCount() - 1);
                            scoreCard.wantButton.setText("想买");
                            scoreCard.wantButton.setBackgroundColor(getResources().getColor(R.color.primary));
                            scoreCard.wantButton.setTextColor(getResources().getColor(R.color.white_text));
                            isWant = false;
                        }
                        else {
                            Toast.makeText(ClubActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

        //  评分按钮点击
        scoreCard.postScoreButton.setOnClickListener(v -> {
            if (!isPost) {
                //  显示对话框（Dialog）
                Dialog dialog = new Dialog(this);
                @SuppressLint("InflateParams")
                View dialogView = LayoutInflater.from(this).inflate(R.layout.post_score_dialog, null);
                dialog.setContentView(dialogView);

                MiniScoreProcessBar scoreBar = dialogView.findViewById(R.id.bar_score);
                Button postButton = dialogView.findViewById(R.id.btn_post);
                postButton.setOnClickListener(v1 -> {
                    ClubRequester.postGrade(this, clubId, scoreBar.getScore(), new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                //  评分提交成功
                                scoreCard.postScoreButton.setText("已打分");
                                scoreCard.postScoreButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                                scoreCard.postScoreButton.setTextColor(getResources().getColor(R.color.secondary_text));
                                isPost = true;
                                //  请求评分数据
                                getClubById();
                            }
                            else {
                                Toast.makeText(ClubActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            //  关闭对话框
                            dialog.dismiss();
                        }
                    });
                });

                dialog.show();
            }
            else {
                scoreCard.postScoreButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                scoreCard.postScoreButton.setTextColor(getResources().getColor(R.color.secondary_text));
                scoreCard.postScoreButton.setEnabled(false);
            }
        });

        //  关注列表点击事件
        bigInfoCard.followCountView.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountListActivity.class);
            intent.putExtra("clubId", clubId);
            intent.putExtra("type", "ClubFansList");
            startActivity(intent);
        });

        //  添加按钮点击事件
        addButton.setOnClickListener(v -> {
            Intent intent = new Intent(this, EditPaperActivity.class);
            intent.putExtra("clubId", clubId);
            startActivity(intent);
        });
    }

    private void loadData() {

        //  加载车友会图片
        clubTitleBar.setImageUrl(FileRequester.CLUB_IMAGE_1_1_BASE_URL + clubId);
        bigInfoCard.setImageUrl(FileRequester.CLUB_IMAGE_1_1_BASE_URL + clubId);
        //  加载背景图
        ImageCacheUtils.loadImage(this, FileRequester.CLUB_IMAGE_16_9_BASE_URL + clubId, bgView);

        //  请求车友会数据
        getClubById();

        //  请求是否关注
        ClubRequester.isFollow(this, clubId, new AfterExecutor<Boolean>() {
            @Override
            public void execute(Result<Boolean> result) {
                Boolean b = result.getData();
                if (result.isSuccess() && b != null && b) {
                    clubTitleBar.followButton.setText("取关");
                    bigInfoCard.followButton.setText("取关");
                    clubTitleBar.followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                    bigInfoCard.followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                    clubTitleBar.followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                    bigInfoCard.followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                    isFollow = true;
                }
                else {
                    clubTitleBar.followButton.setText("关注");
                    bigInfoCard.followButton.setText("关注");
                    clubTitleBar.followButton.setTextColor(getResources().getColor(R.color.white_text));
                    bigInfoCard.followButton.setTextColor(getResources().getColor(R.color.white_text));
                    clubTitleBar.followButton.setBackgroundColor(getResources().getColor(R.color.primary));
                    bigInfoCard.followButton.setBackgroundColor(getResources().getColor(R.color.primary));
                    isFollow = false;
                }
            }
        });

        //  请求是否想买
        ClubRequester.isWant(this, clubId, new AfterExecutor<Boolean>() {
            @Override
            public void execute(Result<Boolean> result) {
                Boolean want = result.getData();
                if (result.isSuccess() && want != null && want) {
                    scoreCard.wantButton.setText("取消");
                    scoreCard.wantButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                    scoreCard.wantButton.setTextColor(getResources().getColor(R.color.secondary_text));
                    isWant = true;
                }
                else {
                    scoreCard.wantButton.setText("想买");
                    scoreCard.wantButton.setBackgroundColor(getResources().getColor(R.color.primary));
                    scoreCard.wantButton.setTextColor(getResources().getColor(R.color.white_text));
                    isWant = false;
                }
            }
        });

        //  请求是否已打分
        ClubRequester.isPostGrade(this, clubId, new AfterExecutor<Boolean>() {
            @Override
            public void execute(Result<Boolean> result) {
                Boolean b = result.getData();
                if (result.isSuccess() && b != null && b) {
                    scoreCard.postScoreButton.setText("已打分");
                    scoreCard.postScoreButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                    scoreCard.postScoreButton.setTextColor(getResources().getColor(R.color.secondary_text));
                    isPost = true;
                }
                else {
                    scoreCard.postScoreButton.setText("打个分");
                    scoreCard.postScoreButton.setBackgroundColor(getResources().getColor(R.color.primary));
                    scoreCard.postScoreButton.setTextColor(getResources().getColor(R.color.white_text));
                    isPost = false;
                }
            }
        });

        //  请求粉丝列表
        list3FansId();

        //  请求动态文章列表
        listPaper();
    }

    private void getClubById() {
        //  请求车友会数据
        ClubRequester.getClubById(this, clubId, new AfterExecutor<ClubDto>() {
            @Override
            public void execute(Result<ClubDto> result) {

                ClubDto dto = result.getData();
                if (result.isSuccess() && dto != null) {
                    //  加载成功，设置标题栏数据
                    clubTitleBar.setName(dto.getName());
                    bigInfoCard.setName(dto.getName());

                    //  计算平均分
                    ClubGradeDto gradeDto = dto.getClubGradeDto();
                    long total = gradeDto.getV5()
                            + gradeDto.getV4()
                            + gradeDto.getV3()
                            + gradeDto.getV2()
                            + gradeDto.getV1();
                    if (total == 0) {
                        total = 1;
                    }
                    long avg = (
                            gradeDto.getV5() * 5
                                    + gradeDto.getV4() * 4
                                    + gradeDto.getV3() * 3
                                    + gradeDto.getV2() * 2
                                    + gradeDto.getV1()) / total;
                    clubTitleBar.setScore(ScoreUtils.scoreToString(avg));

                    bigInfoCard.setPaperCount(dto.getPaperCount());
                    bigInfoCard.setFollowCount(dto.getFansCount());

                    scoreCard.setAdvScore(avg);
                    scoreCard.setPostScoreCount(dto.getPostCount());
                    scoreCard.setWantCount(dto.getWantCount());
                    scoreCard.setGrade1Count(gradeDto.getV5());
                    scoreCard.setGrade2Count(gradeDto.getV4());
                    scoreCard.setGrade3Count(gradeDto.getV3());
                    scoreCard.setGrade4Count(gradeDto.getV2());
                    scoreCard.setGrade5Count(gradeDto.getV1());
                }
            }
        });
    }

    private void list3FansId() {
        ClubRequester.list3FansId(this, clubId, new AfterExecutor<List<Long>>() {
            @Override
            public void execute(Result<List<Long>> result) {
                List<Long> data = result.getData();
                if (result.isSuccess()) {
                    //  请求成功，设置粉丝头像列表
                    String[] array = new String[data.size()];
                    for (int i = 0; i < data.size(); i++) {
                        array[i] = FileRequester.HEADER_BY_ID_BASE_URL + data.get(i);
                    }
                    bigInfoCard.setHeaderImageArray(array);
                    bigInfoCard.setFollowCount(data.size());
                }
            }
        });
    }

    private void listPaper() {

        if (canRequest) {
            canRequest = false;
            //  显示加载动画
            progressBar.setVisibility(View.VISIBLE);
            PaperRequester.listPaperByClubId(this, clubId, startId, new AfterExecutor<List<PaperCardDto>>() {
                @Override
                public void execute(Result<List<PaperCardDto>> result) {
                    if (result.isSuccess()) {
                        //  请求成功，设置数据
                        List<PaperCardDto> data = result.getData();

                        //  追加数据
                        adapter.appendList(data);
                        canRequest = true;

                        //  设置startId
                        if (data.size() > 0) {
                            startId = data.get(data.size() - 1).getId();
                        }

                        //  关闭加载动画
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });
        }
    }
}